# -*- coding: utf-8 -*-

from xml.dom import minidom as XMLParser
from xml import xpath
#from xml.dom.ext.reader import Sax2
#import elementtree.ElementTree as elementTree
from abcommon import HandleError

class GenericXMLParser:
	
	def __init__(self, filename):
		self.filename = filename
		try:
			handler = open(self.filename, "r")
			output = handler.read()
		except IOError:
			handler = open(self.filename, "w")
			self.loadDefaultTree()
			output = handler.read()

		handler.close()
		self.tidyXML(output)
		#self.output = output
		#self.tree = elementTree.parse(self.filename)
		#self.treeRoot = self.tree.getroot()
		self.tree = XMLParser.parse(self.filename).documentElement
		self.document = XMLParser.Document()
		#self.tree = Sax2.Reader().fromStream(self.filename)
		#print dir(self.tree)
		#print self.tree._get_firstChild()
		
	def loadDefaultTree(self): pass
	
	#def cleanUp(self, input):
		# In order with an ET annoyance, which create some default namespaces prefixes,
		# I'v chosen to remove these replacing them in filename's output,
		# to preserve reading of XML-syntax in the specified document.
		#output = input.replace("ns0:","")
		#output = output.replace("ns1:","")
		#output = output.replace(":ns1","")
		#output = output.replace(":ns0","")
		
		# YEAH, DIE STUPID FUCKING NEWLINES! OPTIMIZING IS THE POWAH!
		#output = repr(input).replace(r"\n","").replace(r"\t","").lstrip("'").rstrip("'")
		#handler = open("output.txt", "w")
		#handler.write(output)
		#handler.close()
		#return output
	
	def tidyXML(self, input = None):
		#parsing = not output \
			# Se è None passa a parse(), altrimenti va a parseString()
			#and XMLParser.parse(self.filename).toxml(encoding = "utf-8") \
			#or  XMLParser.parseString(output).toxml(encoding = "utf-8")
		#parsing = self.cleanUp(parsing)
		output = not input \
			and open(self.filename).read() \
			or 	input
		#output = output.encode("utf-8")
		output = unicode(output, "utf-8").replace(u"\n","").replace(u"\t","").replace("\\'", "'").lstrip("'").rstrip("'")
		parsing = XMLParser.parseString(output).toprettyxml(encoding = "utf-8")
		handler = open(self.filename, "w")
		handler.write(parsing)
		handler.close()
		
	def updateTree(self):
		self.tree = XMLParser.parseString(self.tree.toxml(encoding = "utf-8"))
		
	def addTag(self, tagName, XPathExpression, insertAs = "child", tagValue = None, tagAttrs = {}):
		elements = xpath.Evaluate(XPathExpression, self.tree)
		print elements
		tagInstance = self.document.createElement(tagName)
		
		if tagAttrs != {}:
			for name, value in tagAttrs.items():
				tagInstance.setAttribute(name, value)
		if tagValue is not None:
			tagInstance.appendChild(self.document.createTextNode(tagValue))
		
		if len(elements) >= 1:
			
			for current in range(len(elements)):
				print elements[current]
				if insertAs == "child":
					elements[current].appendChild(tagInstance)
					continue
				else:
					currentNode, elBrothers = "", elements[current].parentNode.childNodes
					for child in range(len(elBrothers)):
						try:
							elBrothers[child].tagName
							if elBrothers[child] == elements[current]: 
								currentNode = child
								break
						except AttributeError: continue
						
					if   insertAs == "nextsibling":
						elements[current].parentNode.insertBefore(
							tagInstance, 
							elBrothers[currentNode+1]
						)
					elif insertAs == "prevsibling":
						elements[current].parentNode.insertBefore(
							tagInstance, 
							elBrothers[currentNode-1]
						)
				self.updateTree()
			#handler = open("output.txt", "w")
			#handler.write(self.tree.toxml(encoding = "utf-8"))
			#handler.close()
			
		elif len(elements) == 0:
			HandleError("Config", "Pattern \"%s\" does not match anything." % XPathExpression).runError()
					
		xmlOut = self.tree.toprettyxml(encoding = "utf-8")
		self.tidyXML(xmlOut)
				
			
				
	def setTag(self, tagname, path, position, withvalues = {}): pass
	def delTag(self, tagname, path, position, withvalues = {}): pass
	def getTag(self, tagname, path, position, withvalues = {}): pass
	
	def addAttr(self, values, tagname, path, position, withvalues = {}): pass
	def setAttr(self, values, tagname, path, position, withvalues = {}): pass
	def delAttr(self, values, tagname, path, position, withvalues = {}): pass
	def getAttr(self, values, tagname, path, position, withvalues = {}): pass
			
			
class ConfigXMLParser(GenericXMLParser):
		
	def __init__(self, filename):
		GenericXMLParser.__init__(self, filename)
		#print self.tree
	
	
Config = ConfigXMLParser("settings.xml")
#Config.addTag("prova2","section", withvalues = { "name": "Rete" })
#Config.addTag("figlio","section[2]/option[@name='Max-kbs']")
#Config.addTag("figlio","section[2]/option[@name='Max-kbs']", tagAttrs = { "name" : "Simone" })
#Config.addTag("figlio","section[2]/option[@name='Max-kbs']", tagValue = "Messaggio di prova", tagAttrs = { "name" : "Simone" })
#Config.addTag("fratello_minore","section[2]/option[@name='Max-kbs']","prevsibling")
#Config.addTag("tuasorellafalebocche","section[2]/option[@name='Timeout']","nextsibling")
#Config.addTag("tuasorellainveceno","section[2]/option[@name='Tent-riconnessione']","nextsibling")
#Config.addTag("label2","section[3]/label","nextsibling")
#Config.addTag("label2bis","section[3]/option[1]","prevsibling")
Config.addTag("values","section[3]/option")

